var express = require('express')
var router = express.Router()
var mongoose = require('mongoose')

var Gooods = require('../models/goods')

mongoose.connect('mongodb://127.0.0.1:27017/sweets', {useNewUrlParser:true}, function(err){
    if(err){
        console.log('Connection Error:' + err)
    }else{
        console.log('Connection success!')
    }
})

mongoose.connection.on('connected', function () {
    console.log('MongoDB connected success')
})

mongoose.connection.on('error', function () {
    console.log('MongoDB connected error')
})

mongoose.connection.on('disconnected', function () {
  console.log('MongoDB connected disconnected')
})

// 首页渲染
router.get('/list', function (req, res, next) {
    Gooods.find({}, function (err, doc) {
        if (err) {
            res.json({
                status: 1,
                msg: err.message
            })
        } else {
            res.json({
                status: 0,
                msg: '',
                result: {
                    count: doc.length,
                    list: doc
                }
            })
        }
    })
})

// 从跳转路由里面获取参数，进行商品查询
router.post('/detailClasstify', function(req, res, next) {
    var classtity = req.body.classtify
    console.log(classtity)
    Gooods.find({ classify: classtity }, function (err, doc) {
        if (err) {
            res.json({
                status: 1,
                msg: err.message,
                result: ''
            })
        } else {
            res.json({
                status: 0,
                msg: '',
                result: {
                    count: doc.length,
                    list: doc
                }
            })
        }
    })
})

// 点击进行商品查询
router.get('/checkClasstify', function(req, res, next) {
    var classtity = req.param("classtify")
    console.log('checkClasstify', classtity)
    Gooods.find({ classify: classtity }, function (err, doc) {
        if (err) {
            res.json({
                status: 1,
                msg: err.message,
                result: ''
            })
        } else {
            res.json({
                status: 0,
                msg: '',
                result: {
                    count: doc.length,
                    list: doc
                }
            })
        }
    })
})

// 商品详情
router.get('/detail', function (req, res, next) {
    var productId = req.param('productId')
    Gooods.find({'productId': productId}, function (err, doc) {
        if (err) {
            res.json({
                status: 1,
                msg: err.message,
                result: ''
            })
        } else {
            res.json({
                status: 0,
                msg: '',
                result: {
                    count: doc.length,
                    list: doc
                }
            })
        }
    })
})

// 价格升降序
router.get('/goodsSort', function(req, res, next) {
    let classtify = req.param('classtify')
    Gooods.find({classify: classtify}).sort({"salePrice": 1}).exec(function (err, doc) {
        if (err) {
            res.json({
                status: 1,
                msg: err.message,
                result: ''
            })
        } else {
            res.json({
                status: 0,
                msg: '',
                result: {
                    count: doc.length,
                    list: doc
                }
            })
        }
    })
})

// 加入购物车
router.post('/addCart', function(req, res, next) {
    var userId = 1809104005
    var productId = req.body.productId
    var User = require('../models/users')
    User.findOne({ userId: userId }, function (err, userDoc) {
        if (err) {
            res.json({
                status: 1,
                msg: err.message
            })
        } else {
            if (userDoc) {
                let goodsItem = ''
                userDoc.cartList.forEach((item) => {
                    if (item.productId === productId) {
                        goodsItem = item
                        item.productNum++
                    }
                })
                if (goodsItem) {
                    userDoc.save(function (err2, doc2) {
                        if (err2) {
                            res.json({
                                status: 1,
                                msg: err2.message
                            })
                        } else {
                            res.json({
                                status: 0,
                                msg: '',
                                result: 'suc'
                            })
                        }
                    })
                } else {
                    Gooods.findOne( {productId: productId}, function (err1, doc) {
                        if (err1) {
                            res.json({
                                status: 1,
                                msg: err1.message
                            })
                        } else {
                            if (doc) {
                                doc.productNum = 1
                                doc.checked = 1
                                userDoc.cartList.push(doc)
                                userDoc.save(function (err2, doc) {
                                    if (err2) {
                                        res.json({
                                            status: 1,
                                            msg: err2.message
                                        })
                                    } else {
                                        res.json({
                                            status: 0,
                                            msg: '',
                                            result: 'suc'
                                        })
                                    }
                                })
                            }
                        }
                    })
                }
            }
        }
    })
})

// 添加商品
router.post('/addGoods', function (req, res, next) {
    var productId = req.body.productId
    var productName = req.body.productName
    var classifyName = req.body.classifyName
    var classify = req.body.classify
    var bazaarPrice = req.body.bazaarPrice
    var salePrice = req.body.salePrice
    var productNum = req.body.productNum
    let productImage = req.body.productImage
    Gooods.create({
        productId: productId,
        productName: productName,
        classifyName: classifyName,
        classify: classify,
        bazaarPrice: bazaarPrice,
        salePrice: salePrice,
        productNum: productNum,
        productImage: productImage
    }, function (err, doc) {
        if (err) {
            res.json({
                status: 1,
                msg: err.message,
                result: ''
            })
        } else {
            res.json({
                status: 0,
                msg: '',
                result: '加入成功'
            })
        }
    })
})

router.post('/delete', function (req, res) {
  var productId = req.body.productId
  console.log(productId)
  if (productId.match(/^[0-9a-fA-F]{24}$/)) {
    Gooods.findByIdAndRemove({'_id': productId}, function (err, doc) {
      if (err) {
        res.json({
          status: 1,
          msg: err.message,
          result: ''
        })
      } else {
        res.json({
            status: 0,
            msg: '',
            result: '删除成功'
        })
      }
    })
  }
})

module.exports = router